package com.lori.netshop.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lori.netshop.pojo.CarItem;
import com.lori.netshop.service.CarService;
import com.lori.netshop.util.NetshopResult;

/**
 * 购物车controller
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/cart")
public class CarController {
	@Autowired
	private CarService carServiceimp;
	
	/**
	 * 添加商品进购物车
	 *
	 */
	@RequestMapping(value="add/{itemId}",produces=MediaType.ALL_VALUE+";charset=utf-8")
	@ResponseBody
	public String carAddItem(@PathVariable long itemId, @RequestParam(defaultValue="1") int num,
			HttpServletRequest request,HttpServletResponse response){
		NetshopResult result = carServiceimp.carAddItem(itemId, num, request, response);
		ObjectMapper mapper = new ObjectMapper();
		String json = "";
		try {
			json = mapper.writeValueAsString(result);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}
	/**
	 * 购物车展示
	 */
	@RequestMapping("/cart")
	public String showCar(HttpServletRequest request,HttpServletResponse response,Model model){
		List<CarItem> carItems = carServiceimp.findCarItems(request, response);
		model.addAttribute("cartList", carItems);
		return "cart";
	}
	/**
	 * 修改购物车商品数量
	 */
	@RequestMapping("/update/num/{itemId}/{num}")
	@ResponseBody
	public String updateItemNum(@PathVariable("itemId")long itemId,@PathVariable("num")int num,
			HttpServletRequest request,HttpServletResponse response){
		NetshopResult result = carServiceimp.updateItemNum(itemId, num, request, response);
		ObjectMapper mapper = new ObjectMapper();
		String json = "";
		try {
			json = mapper.writeValueAsString(result);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return json;
	}
	/**
	 * 删除购物车商品
	 *
	 */
	@RequestMapping("/delete/{itemId}")
	public String deleteCarItem(@PathVariable Long itemId, HttpServletRequest request,
			HttpServletResponse response){
		NetshopResult result = carServiceimp.deleteCarItem(itemId, request, response);
		return "redirect:/cart/cart.html";
	}
	
}
